import redis
import json
from datetime import datetime


# 连接 Redis（复用项目配置）
redis_client = redis.Redis(
    host="localhost",
    port=6379,
    db=3,  # 单独使用 DB 3 存储任务元信息（避免与其他 DB 冲突）
    decode_responses=True
)

class TaskRedisManager:
    """管理任务元信息的 Redis 操作类。通过 (job_id, resume_id, task_type) 唯一定位，value中存Celery真实task_id。"""

    @staticmethod
    def _get_task_key(resume_id: int, job_id: int) -> str:
        # 键格式：task:{task_type}:{job_id}:{resume_id}
        return f"task:{job_id}:{resume_id}"

    @staticmethod
    def save_task_meta(resume_id, job_id, task_id, status):
        key = TaskRedisManager._get_task_key(resume_id, job_id)
        print(f"save_task_meta: {key}")
        meta = {
            "task_id": task_id,  # Celery真实task_id
            "status": status,
            "timestamp": datetime.now().isoformat()
        }
        redis_client.setex(key, 86400, json.dumps(meta))  # 24 小时过期

    @staticmethod
    def update_task_status(resume_id, job_id, status):
        key = TaskRedisManager._get_task_key(resume_id, job_id)
        meta = json.loads(redis_client.get(key) or "{}")
        meta["status"] = status
        meta["update_time"] = datetime.now().isoformat()
        redis_client.setex(key, 86400, json.dumps(meta))

    @staticmethod
    def get_task_meta(resume_id: int, job_id: int) -> dict:
        """根据简历ID+职位ID查询任务元信息，返回包含Celery真实task_id的dict"""
        key = TaskRedisManager._get_task_key(resume_id, job_id)
        meta_str = redis_client.get(key)
        return json.loads(meta_str) if meta_str else {}

